package service;

import mapper.CommonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import pojos.admin.AdminInfo;
import pojos.admin.AdminLoginRecord;
import pojos.common.ReplyMessage;
import utils.IpAcquireUtils;
import utils.Md5Utils;
import utils.SpecialCodeReplaceUtil;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;

/**
 * 登录服务处理类
 */
public class CommonLoginService {

    private Logger logger = LoggerFactory.getLogger(CommonLoginService.class);
    private CommonMapper commonMapper;

    @Autowired
    public CommonLoginService(CommonMapper commonMapper) {
        this.commonMapper = commonMapper;
    }

    /**
     * 管理员登录
     */
    public ReplyMessage adminLogin(String name, String password, HttpServletRequest request){
        // 替换name中的特殊字符
        String nameTrans = SpecialCodeReplaceUtil.doReplace(name);
        // 密码加密
        String passwordEn = Md5Utils.getMd5(password);

        ReplyMessage replyMessage = new ReplyMessage();
        try {
            AdminInfo adminInfo = commonMapper.adminLoginCheck(nameTrans);
            if(adminInfo != null){
                int adminId = adminInfo.getId();

                // 系统锁检查
                byte sysLock = adminInfo.getSysLock();
                if(sysLock != 0){
                    replyMessage.setStatus(400);
                    replyMessage.setInfo("当天密码错误次数达到最大限制，请在24小时后重新尝试登录！");
                    return replyMessage;
                }

                // 密码比对
                String queryPswd = adminInfo.getPassword();
                if(queryPswd.equals(passwordEn)){
                    // 保存登录信息
                    String ipAddress = IpAcquireUtils.getVisitIp(request);
                    AdminLoginRecord loginRecord = new AdminLoginRecord();
                    loginRecord.setAdminId(adminId);
                    loginRecord.setIpNum(ipAddress);
                    loginRecord.setLoginTime(new Timestamp(System.currentTimeMillis()));
                    commonMapper.adminLoginRecord(loginRecord);

                    replyMessage.setStatus(200);
                    adminInfo.setPassword("");
                    adminInfo.setName(name);
                    replyMessage.setObject(adminInfo);
                    return replyMessage;
                }

                // 更新密码错误次数
                long errorTime = adminInfo.getErrorTime();
                if(errorTime > 10){
                    // 锁定登录
                    commonMapper.adminAccountLock(adminId);
                    commonMapper.adminAccountAutoUnlock(adminId);
                }
                // 密码错误次数加1
                commonMapper.updateAdminErrorTime(adminId);

                replyMessage.setStatus(400);
                replyMessage.setInfo("密码错误！");
                return replyMessage;
            }
            replyMessage.setStatus(400);
            replyMessage.setInfo("用户不存在！");
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("管理员登录时异常，登录名："+name+"，密码："+password);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常！");
            return replyMessage;
        }
    }

    /**
     * 修改用户密码
     */
    public ReplyMessage updateUserPassword(int id,String role,String password){
        ReplyMessage replyMessage = new ReplyMessage();

        String passwordEn = Md5Utils.getMd5(password);

        try {
            commonMapper.updateUserPassword(role,id,passwordEn);
            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户忘记密码时修改密码异常，用户ID："+id+"，用户角色："+role);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }
}
